package projectbs;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Random;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import projectbs.cmd.CommandFactory;
import projectbs.session.AioTcpSession;
import projectbs.session.SessionPool;

import common.socket.utils.PrintStackTrace;

public class ProjectBSMain {

	static Logger logger = LoggerFactory.getLogger(ProjectBSMain.class);
	static final int SERVER_PORT = 8000;

	public static void main(String[] args) throws IOException {
		CommandFactory.getInstance();
		final AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel
				.open(AsynchronousChannelGroup.withCachedThreadPool(Executors
						.newCachedThreadPool(), Runtime.getRuntime()
						.availableProcessors()));
		server.bind(new InetSocketAddress(SERVER_PORT));
		server.accept(null,
				new CompletionHandler<AsynchronousSocketChannel, Object>() {

					@Override
					public void completed(AsynchronousSocketChannel channel,
							Object attachment) {
						logger.debug("client connected");
						AioTcpSession session = new AioTcpSession(channel);
						session.pendingRead();
						SessionPool.SESSION_POOL.put(session.getSessionId(),
								session);
						server.accept(null, this);	

						String msg = "msg from server";
						Random ran = new Random();
						for (int i = 0; i < 500; i++) {
							msg += (char)(ran.nextInt(100) + 1) + "";
						}
						ByteBuffer buffer = ByteBuffer.allocate(30000);
						// buffer.putInt(msg.length());
						try {
							buffer.put(msg.getBytes("utf8"));
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
						session.response(1, buffer);
					}

					@Override
					public void failed(Throwable exc, Object attachment) {
						PrintStackTrace.print(logger, exc);
					}
				});

		logger.info("socket server started");
	}
}
